package com.cmfi.controller;

import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cmfi.domain.BOM;
import com.cmfi.service.inter.BOMService;
import com.cmfi.utils.Code;
import com.cmfi.utils.Result;

import lombok.extern.slf4j.Slf4j;

//return都是result

@Slf4j
@RestController
@RequestMapping("/api/readme")
public class BOMController {
    @Autowired
    private BOMService bomService;
    static Logger log = LoggerFactory.getLogger(BOMController.class);
    
    @PostMapping("/bom")
    @PreAuthorize("hasAuthority('admin')")
    public Result createBOM(@RequestBody BOM bom){
    	log.info("[BOMController][create] bom:{},", bom);
    	if (bom.getId() != null) {
    		return new Result(Code.SAVE_ERR, "计划ID不为空");
    	}
    	try {
    		// 文件路径
            String filePath = bom.getPath();
            
            // 使用Paths.get创建Path对象
            Path path = Paths.get(filePath);
            
            // 获取文件名，即最后一级目录
            String fileName = path.getFileName().toString();
            
            // 重新塞入文件地址，即文件名
            bom.setPath(fileName);
            bomService.save(bom);
    		return new Result(Code.SAVE_OK, bom);
    	} catch (Exception e) {
    		log.info("REST request to save e,", e);
    		return new Result(Code.SAVE_ERR, e.getMessage());
    	}
    }
    
    /**
     * {@code PUT  /read-mes/:id} : Updates an existing readMe.
     *
     * @param id the id of the readMe to save.
     * @param bom the readMe to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated readMe,
     * or with status {@code 400 (Bad Request)} if the readMe is not valid,
     * or with status {@code 500 (Internal Server Error)} if the readMe couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/bom/{id}")
    @PreAuthorize("hasAuthority('admin')")
	public Result updateBOM(@PathVariable(value = "id", required = false) final Long id,
			@RequestBody BOM bom) {
		log.info("[BOMController][updateBOM] bom:{},", bom);
		if (id == null) {
			return new Result(Code.UPDATE_ERR, "计划ID为空");
		}
		try {
			// 文件路径
            String filePath = bom.getPath();
            
            // 使用Paths.get创建Path对象
            Path path = Paths.get(filePath);
            
            // 获取文件名，即最后一级目录
            String fileName = path.getFileName().toString();
            
            // 重新塞入文件地址，即文件名
            bom.setPath(fileName);
			bomService.update(bom, id);//调用对象！！！！！开头第一个字母小写！！！！！
			return new Result(Code.UPDATE_OK, bom);
		} catch (Exception e) {
			log.error("[BOMController][updateBOM] e,", e);
			return new Result(Code.UPDATE_ERR, e.getMessage());
		}
	}
    
    /**
     * {@code GET  /read-mes} : get all the readMes.
     *
     * @param findByPage the pagination information.
     * @param request a {@link ServerHttpRequest} request.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of readMes in body.
     */
    @GetMapping(value = "/bom", produces = MediaType.APPLICATION_JSON_VALUE)
	public Result getAllBOMs() {
		log.debug("REST request to get a page of BOMs");
		List<BOM> bomList = null;
		long total = 0;
		try {
			bomList = bomService.findAllBOMs();
			total = bomList.size();
		} catch (Exception e) {
			log.error("[BOMController][getAllBOMs] e:{}", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, bomList, total);
	}

    /**
     * {@code GET  /read-mes/:id} : get the "id" readMe.
     *
     * @param id the id of the readMe to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the readMe, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/bom/{id}")
    public Result getBOM(@PathVariable Long id) {
        log.debug("REST request to get BOM : {}", id);
        try {
			bomService.getById(id);
		} catch (Exception e) {
			log.error("[BOMController][getBOM] id: {}", id);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, id);
    }
    
    /**
     * {@code DELETE  /forklift-plans/:id} : delete the "id" readMe.
     *
     * @param id the id of the readMe to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/bom/{id}")
    @PreAuthorize("hasAuthority('admin')")
	public Result deleteBOM(@PathVariable Long id) {
    	log.debug("REST request to delete BOM : {}", id);
		try {
			bomService.delete(id);
		} catch (Exception e) {
			log.error("[BOMController][deleteBOM] id: {}", id);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.DELETE_OK, id);
	}
    
//    /**
//     * {@code GET  /download-pdf/:path} : get the "path" readMe.
//     *
//     * @param path the path of the readMe to retrieve.
//     */
//    @GetMapping("/download-pdf")
//    public ResponseEntity<Resource> downloadPdf(@RequestParam Map<String, Object> params) {
//    	log.debug("REST request to get path : {}", params);
//    // PDF文件路径
//    	String filePath = null;//一页有几个
//		if (params.containsKey("filePath")) {
//			filePath =params.get("filePath").toString();
//		}
//        File file = new File(StringEscapeUtils.unescapeJava(filePath));
//        HttpHeaders header = new HttpHeaders();
//        header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=mysql.pdf");
//    // 设置内容类型为application/pdf
//        header.setContentType(MediaType.APPLICATION_PDF);
//    // 使用FileSystemResource包装文件
//        Resource resource = new FileSystemResource(file);
//    // 返回ResponseEntity
//        return new ResponseEntity<>(resource, header, org.springframework.http.HttpStatus.OK);
//    }
     
    /**
     * {@code GET  /read-mes} : get all the readMes that users have rights to see.
     *
     * @param findByPage the pagination information.
     * @param request a {@link ServerHttpRequest} request.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of readMes in body.
     */
    @GetMapping(value = "/bom/list/{id}")
    public Result getLimitedBOMs(@PathVariable Long id) {
    	log.debug("REST request to get BOM by user's rights: {}", id);
    	List<BOM> limitedBOMList = null;
    	long total = 0;
    	Long roleId = null;
    	try {
    		roleId = bomService.findRoleId(id);
    		limitedBOMList = bomService.findByUser(roleId);
    		total = limitedBOMList.size();
    	} catch (Exception e) {
    		log.error("[BOMController][getLimitedBOMs] e: ", e);
    		return new Result(Code.GET_ERR, e.getMessage());
    	}
    	return new Result(Code.GET_OK, limitedBOMList, total);
   }
    
}

